package com.bieyang.anjia.ui.activity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.bieyang.anjia.R;
import com.bieyang.anjia.module.TNewVerInfo;
import com.bieyang.anjia.utils.Constants;
import com.bieyang.anjia.utils.SharedPrefsUtil;
import com.bieyang.anjia.utils.Show;
import com.bieyang.anjia.utils.Util;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

/**
 * add version_upgrade 添加版本更新
 * 
 * @author wjh
 * 
 */
public class AcTiYan extends BaseActivity {
	Button btnBack, btnLogin;
	LinearLayout btnRegister;
	private Context con;
	protected static final int UPDATA = 0;
	protected static final int PUSHSERVICE_ISRUN = 1;
	protected static final int OK = -555;
	protected static final int MAIN_OK = -553;
	protected static final int SUB_OK = -552;

	// 上一次按下back键时间
	private long exitMillis;

	// version upgrade
	String newVersion;
	boolean isFinish = false;
	private int index = 0;
	private ProgressBar progressBar;
	public Dialog dialog, progressDialog;

	String rVersion, lVersion;

	private Handler Uihandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case UPDATA:
				progressBar.setProgress(index);
				if (index >= 99) {
					progressDialog.dismiss();
				}
				SharedPrefsUtil.putValue(App.mContext, "newVersion", 0);
				break;
			default:
				break;
			}

		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ac_tiyan);
		con = AcTiYan.this;
		initView();
		initData();

	}

	private void initView() {
		OnClick onClick = new OnClick();
		btnBack = (Button) findViewById(R.id.btnBack);
		btnBack.setOnClickListener(onClick);
		btnLogin = (Button) findViewById(R.id.account_login);
		btnLogin.setOnClickListener(onClick);
		btnRegister = (LinearLayout) findViewById(R.id.account_register);
		btnRegister.setOnClickListener(onClick);
	}

	private void initData() {
		// 检测有版本更新
		if (2 == SharedPrefsUtil.getIntValue(this, "newVersion", 0)) {
			popUpVersion(2);
		} else if (3 == SharedPrefsUtil.getIntValue(this, "newVersion", 0)) {
			popUpVersion(3);
		}
	}

	class OnClick implements android.view.View.OnClickListener {
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.btnBack:
				finish();
				break;
			case R.id.account_login:
				startActivity(new Intent(con, AcLogin.class));
				finish();
				break;
			case R.id.account_register:
				startActivity(new Intent(con, AcRegister.class));
				finish();
				break;
			default:
				break;
			}
		}

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		if (keyCode == KeyEvent.KEYCODE_BACK) {
			long exitMillis = System.currentTimeMillis();
			if (exitMillis - this.exitMillis < 5000) {
				finish();
			} else {
				Show.toast(con, getString(R.string.main_press_again));
			}
			this.exitMillis = exitMillis;
			return false;
		}
		return super.onKeyDown(keyCode, event);
	}

	void popUpVersion(final int typeUpgrade) {
		dialog = new Dialog(con);
		LayoutInflater inflater = LayoutInflater.from(con);// 初始化
		View view = inflater.inflate(R.layout.pop_version_upgrade, null);
		
		TextView tvTitle = (TextView)view.findViewById(R.id.tvTitle);
		tvTitle.setText("v"+App.verinfo.sNewVerNo+"升级内容");
		
		TextView tvUpContent = (TextView) view.findViewById(R.id.tvUpContent);
		tvUpContent.setText(App.verinfo.sUpMsg);

		// 点确定，开始下载更新
		view.findViewById(R.id.exitBtn0).setOnClickListener(
				new OnClickListener() {
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						if (!Util.hasSdcard()) {
							Show.toast(con, R.string.no_sdcard);
							dialog.dismiss();
							return;
						}

						LayoutInflater inflater = LayoutInflater.from(con);
						progressDialog = new Dialog(con);
						progressDialog.setCancelable(false);
						View popView = inflater.inflate(
								R.layout.pop_progress_layout, null);
						progressBar = (ProgressBar) popView
								.findViewById(R.id.progressBar1);
						progressBar.setMax(100);

						progressDialog.getWindow();
						progressDialog
								.requestWindowFeature(Window.FEATURE_NO_TITLE);
						progressDialog.setContentView(popView);
						downFile(App.verinfo.sUpDownLinkAddr);
					}
				});

		// 点取消 ，弹窗消失
		view.findViewById(R.id.exitBtn1).setOnClickListener(
				new OnClickListener() {
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						if (3 == typeUpgrade) {
							finish();
						} else {
							dialog.dismiss();
							SharedPrefsUtil.putValue(App.mContext,
									"newVersion", 1);
						}
					}
				});
		dialog.getWindow();
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setCanceledOnTouchOutside(true);
		dialog.setContentView(view);
		dialog.show();
	}

	public void downFile(final String url) {
		dialog.dismiss();
		progressDialog.show();
		Log.d("iFileSize", App.verinfo.sFileName + "-size:-"
				+ App.verinfo.iFileSize);
		Log.d("iurl", url);

		new Thread() {
			public void run() {
				HttpClient client = new DefaultHttpClient();
				HttpGet get = new HttpGet(url);
				HttpResponse response;
				try {
					response = client.execute(get);
					HttpEntity entity = response.getEntity();
					// long length = entity.getContentLength();
					InputStream is = entity.getContent();
					FileOutputStream fileOutputStream = null;
					if (is != null) {
						File file = new File(
								Environment.getExternalStorageDirectory(),
								App.verinfo.sFileName); // Config.UPDATE_SAVENAME
						fileOutputStream = new FileOutputStream(file);
						byte[] buf = new byte[1024];
						int ch = -1;
						int count = 0;
						while ((ch = is.read(buf)) != -1) {
							fileOutputStream.write(buf, 0, ch);
							count += ch;

							index = (int) (count * 100)
									/ (App.verinfo.iFileSize); //
							// fileName
							Log.d("index", String.valueOf(index));
							AcTiYan.this.progressDialog = progressDialog;
							Uihandler.sendEmptyMessage(UPDATA);

						}
					}
					fileOutputStream.flush();
					if (fileOutputStream != null) {
						fileOutputStream.close();
					}
					down();
				} catch (ClientProtocolException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}.start();
	}

	//
	public void down() {
		Uihandler.post(new Runnable() {
			public void run() {
				progressDialog.cancel();
				update();
			}
		});
	}

	// INSTALL APK
	public void update() {
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setDataAndType(Uri.fromFile(new File(Environment
				.getExternalStorageDirectory(), App.verinfo.sFileName)),
				"application/vnd.android.package-archive"); // Config.UPDATE_SAVENAME
		startActivity(intent);
	}

}
